package com.seed.application.service;

import cn.hutool.core.bean.BeanUtil;
import com.mybatisflex.core.BaseMapper;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.row.Row;
import com.mybatisflex.core.row.RowUtil;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.seed.application.web.WebContext;
import com.seed.core.pojo.GetVO;
import com.seed.core.pojo.SetDTO;
import com.seed.core.pojo.StatPage;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

public class BaseService<M extends BaseMapper<T>, T> extends ServiceImpl<M, T> {

    @Autowired
    protected WebContext web;

//    @Autowired
    protected SeedService seedService;

    private final Class<T> entityClass;

    public BaseService(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    public StatPage<T> page(Integer pageNumber, Integer pageSize) {
        StatPage<Row> statPage = seedService.page(pageNumber, pageSize);
        Page<Row> page = statPage.getPage();
        List<T> list = page.getRecords().stream()
                .map(row -> RowUtil.toEntity(row, entityClass))
                .toList();

        Page<T> newPage = new Page<>(list, page.getPageNumber(), page.getPageSize(), page.getTotalRow());
        return new StatPage<>(newPage, statPage.getStats());
    }

    public boolean save(T t) {
        Map<String, Object> map = BeanUtil.beanToMap(t);
        Row data = new Row();
        data.putAll(map);
        seedService.save(data);
        return true;
    }

    public boolean update(T t) {
        Map<String, Object> map = BeanUtil.beanToMap(t);
        Row data = new Row();
        data.putAll(map);
        seedService.update(data);
        return true;
    }

    public T detail(Serializable id) {
        Row row = seedService.detail(id);
        return RowUtil.toEntity(row, entityClass);
    }

    public boolean remove(Serializable id) {
        return seedService.remove(id);
    }

    public GetVO get(Serializable id) {
        return seedService.get(id);
    }

    public boolean set(SetDTO dto) {
        return seedService.set(dto);
    }

    public Map<String, Object> stat() {
        return seedService.stat();
    }
}
